package com.zz.tijian.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.tijian.entity.Topic;
import com.zz.tijian.entity.doc.TopicDoc;
import com.zz.tijian.entity.req.AddTopicDto;
import com.zz.tijian.entity.req.CurrentUserInfo;
import com.zz.tijian.entity.req.TopicDto;
import com.zz.tijian.entity.res.Result;
import com.zz.tijian.mapper.TopicMapper;
import com.zz.tijian.repository.TopicRepository;
import com.zz.tijian.service.TopicService;
import com.zz.tijian.utils.UserContext;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.MultiGetItem;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* @author 86137
* @description 针对表【topic】的数据库操作Service实现
* @createDate 2024-06-24 16:11:56
*/
@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic>
    implements TopicService {

    @Autowired
    private TopicRepository topicRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public Result<List<Topic>> getTopic(TopicDto topicDto) {
        String key = topicDto.getSearchKeyword();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if(key == null || key.trim().length() == 0){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }

        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery);

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(functionScoreQuery)
                .build();

        //List<Topic> topics = elasticsearchRestTemplate.queryForList(searchQuery, Topic.class);
        SearchHits<TopicDoc> search = elasticsearchRestTemplate.search(searchQuery, TopicDoc.class);
        List<Topic> collect = search.getSearchHits().stream().map(hit -> {
            TopicDoc content = hit.getContent();
            Topic topic = new Topic();
            BeanUtils.copyProperties(content, topic);
            return topic;
        }).collect(Collectors.toList());

        return Result.ok(collect);
    }

    @Override
    public Result<Topic> getTopicById(Integer topicId) {
        LambdaQueryWrapper<Topic>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Topic::getId,topicId);
        Topic one = this.getOne(queryWrapper);
        return Result.ok(one);
    }

    @Override
    public Result<Boolean> addTopic(AddTopicDto addTopicDto) {
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        Topic topic = new Topic();
        BeanUtils.copyProperties(addTopicDto,topic);
        topic.setUserId(currentUserInfo.getUserId());
        topic.setRealName(currentUserInfo.getRealName());
        this.save(topic);
        Topic one = this.getById(topic.getId());
        TopicDoc topicDoc = new TopicDoc();
        BeanUtils.copyProperties(one,topicDoc);
        this.save(topicDoc);
        return Result.ok(true);
    }




    public Topic save(TopicDoc topicDoc)
    {
        return topicRepository.save(topicDoc);
    }

    public Iterable<TopicDoc> findAll() {
        return topicRepository.findAll();
    }

    public Optional<TopicDoc> findById(Integer id) {
        return topicRepository.findById(id);
    }

    public void deleteById(Integer id) {
        topicRepository.deleteById(id);
    }

    @Override
    public void refreshFromDB() {
        this.list().forEach(topic -> {
            TopicDoc topicDoc = new TopicDoc();
            BeanUtils.copyProperties(topic, topicDoc);
            this.save(topicDoc);
        });
    }
}




